<?php
namespace app\shop\service\company;
use app\shop\model\company\TrainFile;
use app\shop\model\company\Staff;
use app\shop\model\company\Station;
use app\shop\model\company\TrainStudent;
use app\shop\validate\company\Train as TrainValidate;
use app\shop\model\file\UploadFile;
use app\shop\model\company\TrainLog;
use app\common\service\Result;
class Train
{
    public function files($data)
    {
        $app_id = request()->app_id;
        $map = [
            ['app_id', '=', $app_id]
        ];
        if (isset($data['department_id']) && $data['department_id']) {
            $map[] = ['department_id', 'in', $data['department_id']];
        }
        if (isset($data['station_id']) && $data['station_id']) {
            $map[] = ['station_id', '=', $data['station_id']];
        }
        $page_size = $data['page_size'] ?? 20;
        $lists = TrainFile::where($map)->with(['department', 'station', 'author'])->order('sort desc,id desc')
            ->paginate($page_size);
        return Result::success($lists);
    }

    public function students($data)
    {
        $map = [];
        if (isset($data['station_id']) && $data['station_id']) {
            $map[] = ['station_id', 'in', $data['station_id']];
        }
        $user_name = $data['user_name'] ?? "";
        $page_size = $data['page_size'] ?? 20;
        $lists = TrainStudent::withJoin([
            'user' => function ($query) use ($user_name) {
                if ($user_name) {
                    $query->where('user_id|real_name|mobile', 'like', "%{$user_name}%");
                }
            },
        ])->with(['department', 'station'])->where($map)->append(['progress', 'status_text'])->order('status,user_id desc')->paginate($page_size);
        return Result::success($lists);
    }

    public function isTrainer($data)
    {
        $app_id = request()->app_id;
        $user_id = request()->user_id;
        if(!$user_id){
            return Result::success(['is_trainer' => false]);
        }
        $map = [
            ['app_id', '=', $app_id],
            ['trainer', '=', $user_id],
        ];
        $station_id = $data['station_id'] ?? 0;
        if ($station_id) {
            $map[] = ['id', '=', $station_id];
        }
        $info = Station::where($map)->find();
        return Result::success(['is_trainer' => $info ? true : false]);
    }

    public function saveFile($data)
    {
        try {
            validate(TrainValidate::class)->scene('saveFile')->check($data);
            $app_id = request()->app_id;
            $file_ids = $data['file_ids'];
            $files = UploadFile::whereIn('file_id', $file_ids)->select();
            $saveData = [];
            foreach ($files as $v) {
                $saveData[] = [
                    'app_id' => $app_id,
                    'file_name' => $v['real_name'],
                    'file_url' => $v->file_path,
                    'department_id' => $data['department_id'],
                    'station_id' => $data['station_id'],
                    'add_user' => $data['add_user'] ?? 0,
                    'download_num' => 0,
                ];
            }
            (new TrainFile)->saveAll($saveData);
            return Result::success();
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function addStudent($data)
    {
        try {
            validate(TrainValidate::class)->scene('addStudent')->check($data);
            $app_id = request()->app_id;
            $user_id = $data['user_id'];
            $staff = Staff::find($user_id);
            if (!$staff) {
                throw new \Exception('员工不存在');
            }
            $student = TrainStudent::find($user_id);
            if ($student) {
                throw new \Exception('学员已存在');
            }
            $student = TrainStudent::create([
                'app_id' => $app_id,
                'user_id' => $user_id,
                'department_id' => $staff['department_id'],
                'station_id' => $staff['station_id'],
            ]);
            return Result::success();
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function trainStation($data)
    {
        try {
            $app_id = request()->app_id;
            $department_id = $data['department_id'] ?? 0;
            $station_id = $data['station_id'] ?? 0;
            $map = [
                ['app_id', '=', $app_id],
            ];
            if ($department_id) {
                $map[] = ['department_id', '=', $department_id];
            }
            if ($station_id) {
                $map[] = ['id', '=', $station_id];
            }
            $lists = Station::where($map)->with([
                'trainerUser',
                'department'
            ])->append(['student_count'])->order('department_id,sort desc')->select();
            return Result::success($lists);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function trainDetail($user_id)
    {
        try {
            $map = [
                ['user_id', '=', $user_id],
            ];
            $student = TrainStudent::where($map)->with([
                'department',
                'station',
            ])->find()->bindAttr('user', ['real_name', 'mobile', 'avatarUrl'])->append(['status_text'])->bindAttr('staff', ['job_id'])->toArray();
            return Result::success($student);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function trainLog($data)
    {
        try {
            $student_id = $data['student_id'] ?? 0;
            $page_size = $data['page_size'] ?? 20;
            $map = [];
            if ($student_id) {
                $map[] = ['user_id', '=', $student_id];
            }
            $lists = TrainLog::where($map)->with([
                'trainerUser' => function ($query) {
                    $query->field('user_id,real_name,mobile');
                }
            ])->order('id desc')->paginate($page_size);
            return Result::success($lists);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    //结束培训
    public function doneTrain($user_id)
    {
        try {
            $app_id = request()->app_id;
            $user_id = $user_id ?? 0;
            $map = [
                ['app_id', '=', $app_id],
                ['user_id', '=', $user_id],
            ];
            $student = TrainStudent::where($map)->find();
            if (!$student) {
                throw new \Exception('学员不存在');
            }
            $student->status = 1;
            $student->save();
            return Result::success();
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function delFile($id)
    {
        try {
            $app_id = request()->app_id;
            $map = [
                ['app_id', '=', $app_id],
                ['id', '=', $id],
            ];
            $file = TrainFile::where($map)->find();
            if (!$file) {
                throw new \Exception('文件不存在');
            }
            $file->delete();
            return Result::success();
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function saveLog($data)
    {
        try {
            validate(TrainValidate::class)->scene('saveLog')->check($data);
            $user_id = $data['user_id'] ?? 0;
            $student = TrainStudent::find($user_id);
            if (!$student || $student->status == TrainStudent::STATION_DONE) {
                throw new \Exception('学员不存在或已完成培训');
            }
            $content = $data['content'] ?? '';
            TrainLog::create([
                'user_id' => $user_id,
                'content' => $content,
                'progress' => $data['progress'] ?? "",
                'result' => $data['result'] ?? "",
                'trainer' => $data['trainer'] ?? request()->user_id,
            ]);
            $finish = $data['finish'] ?? false;
            if ($finish) {        //完成培训
                $student->status = TrainStudent::STATION_DONE;
                $student->save();
            }
            return Result::success();
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }
}